package cn.tedu.icop.common.advice;
import cn.tedu.icop.api.model.RestResult;
import cn.tedu.icop.api.model.RestResultUtils;
import cn.tedu.icop.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ServiceException.class)
    public RestResult handleServiceException(ServiceException e) {
        System.out.println("e="+e);
        e.printStackTrace();
        return RestResultUtils.failedWithMsg(e.getCode(),e.getMessage());
    }
    @ExceptionHandler(BindException.class)
    public RestResult handleBindException(BindException e) {
        String message = e.getFieldError().getDefaultMessage();
        return RestResultUtils.failed( message);
    }
    @ExceptionHandler(AccessDeniedException.class)
    public RestResult handleAccessDeniedException(AccessDeniedException e) {
        String message = "您当前登录的账号无此操作权限！";
        return RestResultUtils.failedWithMsg(403, message);
    }
    @ExceptionHandler(Throwable.class)
    public RestResult handleThrowable(Throwable e) {
        String message = "服务器忙，请稍后再试！【同学们，在开发时，如果看到这句话，你应该在服务器端控制台查看实际出现的异常及相关信息，并在全局异常处理器中补充对此异常的处理】";
        // e.printStackTrace(); // 在生产环境中禁止使用此语句输出异常信息
        log.warn("", e);
        return RestResultUtils.failedWithMsg(500, message);
    }

}
